import pdb
import sys
import os

project_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(project_path)
from utils import ArgumentParser, ConfigLoader, LOG
from model import GLMModel, OpenAIModel
from translator import PDFTranslator


def call_back(task_id, output_file_path):
    import requests
    url = 'http://127.0.0.1:8000/translator/call_back/'
    data = {
        'task_id': task_id,
        'output_file_path': output_file_path,
    }
    response = requests.post(url, data=data)
    print(response.text)


def run():
    # 命令行配置读取
    argument_parser = ArgumentParser()
    args = argument_parser.parse_arguments()

    # 获取模型参数
    model_name = args.openai_model
    api_key = args.openai_api_key
    base_url = args.openai_base_url
    book = args.book
    task_id = args.task_id
    file_format = args.file_format
    language = args.language if args.language else '中文'
    pages = args.pages if args.pages else None

    # 输入文件
    relative_pdf_file_path = os.path.join(project_path, book)

    if not model_name:
        LOG.error("缺少model_name")
        exit(1)
    if not api_key:
        LOG.error("缺少api_key")
        exit(1)
    if not base_url:
        LOG.error("缺少base_url")
        exit(1)

    # 实例化模型
    model = OpenAIModel(base_url=base_url, model=model_name, api_key=api_key)
    # 实例化 PDFTranslator 类，并调用 translate_pdf() 方法
    translator = PDFTranslator(model)

    print('后台翻译开始')
    print(model_name, api_key, base_url, task_id, book, file_format)
    new_output_file_path = translator.translate_pdf(
        pdf_file_path=relative_pdf_file_path,
        file_format=file_format,
        target_language=language,
        pages=pages,
    )
    print(new_output_file_path)
    # 回调翻译完成
    call_back(task_id, new_output_file_path)


if __name__ == "__main__":
    run()
